import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Upload,
  FileCode2,
  AlertCircle,
  Wand2,
  TestTube2,
  RotateCcw,
  Download,
} from "lucide-react";
import { UploadFile } from "@/api/integrations";
import { previewWordTemplate } from "@/api/functions";
// Removed: import { convertWordToMarkdown } from '@/api/functions'; // Now dynamically imported

export default function WordTemplateUploader({
  template,
  onMarkdownGenerated,
  onUploadComplete,
}) {
  const [isUploading, setIsUploading] = useState(false);
  const [isTesting, setIsTesting] = useState(false);
  const [isConverting, setIsConverting] = useState(false);

  const handleConvertToMarkdown = async (
    uploadedUrl = null,
    uploadedFilename = null
  ) => {
    // Determine the URL and fileName to use
    const fileUrl = uploadedUrl || template.word_template_url;
    const currentFilename = uploadedFilename || template.word_template_filename;

    if (!fileUrl) {
      alert("没有可用的Word模板文件");
      return;
    }

    setIsConverting(true);
    try {
      // Dynamic import of convertWordToMarkdown as per outline
      const { convertWordToMarkdown } = await import("@/api/functions");
      const response = await convertWordToMarkdown({
        fileUrl,
        fileName: currentFilename,
      });
      const result = response.data; // The existing code uses response.data

      if (result.success) {
        let markdown = result.markdown;

        // Normalize newlines: unify to \n
        markdown = markdown.replace(/\r\n/g, "\n").replace(/\r/g, "\n");

        // Ensure proper paragraph spacing: compress multiple newlines to double newline
        markdown = markdown.replace(/\n{3,}/g, "\n\n");

        // If content is still largely on one line, try adding newlines after Chinese punctuation
        // This is a heuristic to help format text that might come as a single long line.
        if (!markdown.includes("\n") && /[。；]/.test(markdown)) {
          markdown = markdown.replace(/。\s*/g, "。\n\n"); // Add double newline after full stop
          markdown = markdown.replace(/；\s*/g, "；\n"); // Add single newline after semicolon
        }

        onMarkdownGenerated(markdown.trim());
        alert("已成功将Word内容转换为Markdown！");
      } else {
        throw new Error(result.error || "转换失败");
      }
    } catch (error) {
      console.error("转换为Markdown失败:", error);
      const errorMessage =
        error.response?.data?.error || error.message || "发生未知错误";
      alert(`转换为Markdown失败: ${errorMessage}`);
    } finally {
      setIsConverting(false);
    }
  };

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    setIsUploading(true);
    try {
      const uploadResult = await UploadFile({ file });
      if (!uploadResult?.fileUrl) throw new Error("文件上传失败");

      // 修复：确保传递正确的参数结构给回调函数
      const callbackData = {
        url: uploadResult.fileUrl,
        fileName: file.name,
      };

      console.log("准备调用onUploadComplete，参数:", callbackData); // 调试日志

      // 核心修改：上传完成后，调用onUploadComplete保存到模板
      if (onUploadComplete && typeof onUploadComplete === "function") {
        await onUploadComplete(callbackData);
      } else {
        console.error("onUploadComplete 不是一个有效的函数:", onUploadComplete);
      }

      // 自动触发转换
      await handleConvertToMarkdown(uploadResult.fileUrl, file.name);
    } catch (error) {
      console.error("Word模板上传过程失败:", error);
      alert(`上传失败: ${error.message || "未知错误"}`);
    } finally {
      setIsUploading(false);
      event.target.value = "";
    }
  };

  const handleTestTemplate = async () => {
    if (!template.word_template_url) {
      alert("请先上传一个Word模板");
      return;
    }
    setIsTesting(true);
    try {
      const response = await previewWordTemplate({
        templateUrl: template.word_template_url,
      });
      const result = response.data;

      let alertMessage = `模板验证${result.success ? "成功" : "失败"}！\n\n${
        result.message
      }`;
      if (result.details && Array.isArray(result.details)) {
        alertMessage += "\n\n--- 详情 ---\n" + result.details.join("\n");
      }
      alert(alertMessage);
    } catch (error) {
      const errorData = error.response?.data;
      let alertMessage = `模板测试时发生错误: ${
        errorData?.message || error.message
      }`;
      if (errorData?.details && Array.isArray(errorData.details)) {
        alertMessage += "\n\n--- 详情 ---\n" + errorData.details.join("\n");
      }
      alert(alertMessage);
    } finally {
      setIsTesting(false);
    }
  };

  // 新增：下载Word模板功能
  const handleDownloadTemplate = () => {
    if (!template.word_template_url) {
      alert("没有可下载的Word模板文件");
      return;
    }

    const link = document.createElement("a");
    link.href = template.word_template_url;
    link.download = template.word_template_filename || "word_template.docx";
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <Card className="max-w-lg mx-auto">
      <CardHeader>
        <CardTitle className="text-base">Word母版文件 (.docx)</CardTitle>
        <CardDescription>
          上传用于最终生成Word文档的模板文件。上传后将自动保存并转换为Markdown内容。
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {template.word_template_url ? (
          <div className="space-y-3">
            <div className="flex items-center gap-2 p-3 bg-gray-100 rounded-md border">
              <FileCode2 className="w-5 h-5 text-gray-500 shrink-0" />
              <span
                className="text-sm font-medium text-gray-800 truncate flex-1"
                title={template.word_template_filename}
              >
                {template.word_template_filename}
              </span>
            </div>

            {/* 新增：下载按钮 */}
            <Button
              onClick={handleDownloadTemplate}
              variant="outline"
              className="w-full"
            >
              <Download className="w-4 h-4 mr-2" />
              下载Word模板
            </Button>

            <div className="grid grid-cols-2 gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={handleTestTemplate}
                disabled={isTesting}
              >
                {isTesting ? (
                  "测试中..."
                ) : (
                  <>
                    <TestTube2 className="w-4 h-4 mr-1" /> 测试变量
                  </>
                )}
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handleConvertToMarkdown()}
                disabled={isConverting}
              >
                {isConverting ? (
                  "转换中..."
                ) : (
                  <>
                    <Wand2 className="w-4 h-4 mr-1" /> 重新转换
                  </>
                )}
              </Button>
            </div>

            <Label htmlFor="replace-word-file" className="w-full">
              <Button variant="secondary" className="w-full" asChild>
                <span>
                  <RotateCcw className="w-4 h-4 mr-2" /> 替换文件
                </span>
              </Button>
            </Label>
            <input
              id="replace-word-file"
              type="file"
              accept=".doc,.docx"
              onChange={handleFileChange}
              className="hidden"
            />
          </div>
        ) : (
          <div>
            <Label
              htmlFor="word-upload"
              className="cursor-pointer flex flex-col items-center justify-center w-full h-32 border-2 border-dashed rounded-lg hover:bg-gray-50"
            >
              <Upload className="w-8 h-8 text-gray-400 mb-2" />
              <span className="text-sm text-gray-600">点击上传 .docx 文件</span>
              <span className="text-xs text-gray-500">
                将自动保存并转换为Markdown
              </span>
            </Label>
            <input
              id="word-upload"
              type="file"
              accept=".doc,.docx"
              onChange={handleFileChange}
              className="hidden"
            />
          </div>
        )}
        {isUploading && <p className="text-sm text-center">上传中...</p>}
        <div className="flex items-start gap-2 p-3 bg-yellow-50 text-yellow-800 rounded-lg border border-yellow-200">
          <AlertCircle className="w-5 h-5 mt-0.5 shrink-0" />
          <p className="text-xs">
            Word母版文件用于最终生成文档，上传后会自动保存到此模板并转换为Markdown内容。您对两边的修改是独立的，可以随时从Word母版重新转换来覆盖Markdown内容。
          </p>
        </div>
      </CardContent>
    </Card>
  );
}
